const User = require('../models/user');
const Department = require('../models/department');
const ObjectId = require('mongodb').ObjectId

const Task = require('../models/task');
const jwt = require('jsonwebtoken');
const {secretKey} = require( '../config' )
const multer = require('multer');
const fs = require('fs')
const path = require('path');



const createUser = async (req, res, next) => {
    try {
        const user = new User(req.body);
        user.taskList = generateTasks()
        await user.save();
        const token = generateToken(user)
        res.status(200).json({
            status: 'success',
            token:token
        });
    } catch (error) {
        res.status(400).json({
            status: 'error',
            errorMessage: error.message,
        });
    }
};

const login = async (req, res, next) => {
   console.log(req.body)

    try {
        const user = await User.findOne(req.body);
        if (user instanceof Object) {
            const token = generateToken(user)
            
            // 发送token
            res.status(200).json({
                success: true,
                message: '登录成功',
                token: token,
                userInfo:{
                    nickname:user.nickname,
                    avatar:user.avatar,
                    role:user.role
                }
            });
        } else {
            res.status(400).json({
                status: 'error',
                message: 'Username or password are wrong',
            });
        }
    } catch (error) {
        res.status(400).json({
            status: 'error',
            errorMessage: error.message,
        });
    }
};

const getUserAllInfo = async(req,res,next) => {

  const userId = req.user.userId;

  try{
    const user = await User.findById(userId)

    res.status(200).json({
      userInfo:{
        personalSignature:user.personalSignature,
        role:user.role,
        department:user.department,
        nickname:user.nickname,
        phone:user.phone,
        email:user.email
      }
    })
  }catch (error) {
    res.status(400).json({
        status: 'error',
        errorMessage: error.message,
    });
}
  



}

const afterLogin = async(req,res) => {
    const headers = req.headers;
    console.log(headers)
    const token = headers['authorization'].split(' ')[1]
    jwt.verify(token,secretKey,(error,payload)=>{
        if(error) res.status(403)
        res.json({
            message:"认证成功",
            payload:payload
        })
    })
}

const updateUserBasicInfo = async (req,res) =>{
  const userId = req.user.userId;


  try{ 
    const user = User.findByIdAndUpdate(userId,{
      ...(req.body.nickname && { nickname: req.body.nickname }),
      ...(req.body.personalSignature && { personalSignature: req.body.personalSignature })
  }).exec();
  res.status(200).json(
      req.body
  )}catch(error){
    res.status(400).json({
      status: 'error',
      errorMessage: error.message,
  })
}
}

const initUserInfo = async(req,res) => {
    const userId = req.user.userId;
    console.log(typeof(req.body['departmentId[]']))
    

    let formataArr = []

    // 封装数组
    if(typeof(req.body['departmentId[]']) == 'string')
    {
        formataArr.push(req.body['departmentId[]'])
        
        
    }else{
        formataArr = req.body['departmentId[]']
        
    }


  
    const parentDepartment = await Department.findById(
        new ObjectId(formataArr[0]));
    
  
    

    if (!parentDepartment) {
      return res.status(404).json({ message: 'Parent department not found' });
    }
    
    if (formataArr.length === 1) {
      parentDepartment.users.push(userId);
    } else {
      const childDepartment = parentDepartment.children.find(
        (child) => child._id.toString() === formataArr[1].toString()
      );
    
      if (!childDepartment) {
        return res.status(404).json({ message: 'Child department not found' });
      }
    
      childDepartment.users.push(userId);
    }
    
    await parentDepartment.save();


    let userDepartment = {};

    
    if(formataArr.length === 1)
    {
        userDepartment.departmentId = formataArr[0],
        userDepartment.jobTitle = '员工'
    }else{
        userDepartment.departmentId = formataArr[1],
        userDepartment.jobTitle = '员工'
    }

    const user = User.findByIdAndUpdate(userId,{
        nickname: req.body.nickname,
        phone: req.body.phone,
        email: req.body.email,
        $push: { department: userDepartment }
    }).exec();

    console.log(user)
  


    res.status(200).json(
        req.body
    );
}

const generateToken = (user) => {
    const payload = {
      userId: user._id,
        account:user.account
    };
    const options = {
        expiresIn: '7d'
    };


    return jwt.sign(payload, secretKey, options);
};

function generateTasks() {
    const tasks = []
    
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const currentDate = `${year}-${month}-${day}`;

    for(let i=0; i<5; i++){
      const task = new Task({
        content: ['编写测试代码并运行，检查代码的正确性和覆盖率。',
                  '完成用户登录、注册功能的前端开发，包括表单验证和错误提示。', 
                  '设计并实现一个在线聊天室，支持文字和表情消息发送、接收、展示，具有响应式布局。',
                  '优化数据库查询效率，降低系统响应时间，提高用户体验。'][Math.floor(Math.random() * 4)],
        status: "doing",
        level: ['normal', 'priority', 'important', 'emergent'][Math.floor(Math.random() * 4)],
        timestamp:currentDate
      })
      tasks.push(task)
      console.log(tasks)
    }
    return tasks
  };

const getAvatar = async (req,res) => {
    const userId = req.user.userId;

    // Find the user in the database
    const user = await User.findById(userId);
  
    if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
    res.status(200).json({
        avatar: user.avatar
    })
};

const uploadAvatar = async (req, res) => {
    try {
      // Check if a file was uploaded
      if (!req.file) {
        return res.status(400).json({ message: 'Please upload a file' });
      }
  
      // Get the user ID from the request params
      const userId = req.user.userId;
  
      // Find the user in the database
      const user = await User.findById(userId);
  
      // Check if the user exists
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
  
      // Delete the old avatar file if it exists
      if (user.avatar && fs.existsSync(user.avatar)) {
        fs.unlinkSync(user.avatar);
      }
  
      user.avatar = req.file.path;
      // Save the updated user document to the database
      await user.save();
  
      // Return the updated user document with the new avatar path
      res.status(200).json({
        avatar:user.avatar
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({ message: 'Server error' });
    }
  };

  const deleteUserById = async (req, res) => {
    const userId = req.params.userId;
  
    try {
      // 使用 findByIdAndDelete 方法查找并删除指定 ID 的用户
      const user = await User.findByIdAndDelete(userId);
  
      if (!user) {
        return res.status(404).json({ message: '找不到指定用户' });
      }
  
      res.json({ message: '用户已成功删除' });
    } catch (error) {
      console.log(error);
      res.status(500).json({ message: '服务器错误' });
    }
  }
const checkAdminPermission = async (req, res, next) => {
    const userId = req.user.userId;
    try {
      const user = await User.findById(userId);
      if (user.role === 'admin') {
        next();
      } else {
        res.status(403).json({ message: '权限不足' });
      }
    } catch (error) {
      res.status(500).json({ message: '服务器错误' });
    }
  };
  
const updateUserById = async (req, res) => {
    const userId = req.params.userId;
  
    try {
      // 使用 findByIdAndUpdate 方法查找并更新指定 ID 的用户
      const updatedUser = await User.findByIdAndUpdate(
        userId,                    // 要更新的文档的 ID
        req.body,                 // 更新的数据
        { new: true, runValidators: true } // 配置项
      );
  
      if (!updatedUser) {
        return res.status(404).json({ message: '找不到指定用户' });
      }
  
      res.json({ message: '用户数据已成功更新' });
    } catch (error) {
      console.log(error);
      res.status(500).json({ message: '服务器错误' });
    }
  }


const getAllUsers = async(req,res) =>{
  try {
    const users = await User.find({})
    .select('personalSignature role _id account createdAt nickname avatar phone department');;
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }

}
  
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'public/uploads/avatars');
    },
    filename: (req, file, cb) => {
      const ext = path.extname(file.originalname);
      const fileName = `${file.fieldname}-${Date.now()}${ext}`;
      cb(null, fileName);
    }
  });


const upload = multer({
  storage,
  limits: { fileSize: 1024 * 1024 * 5 }, // 5MB
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype === 'image/png' ||
      file.mimetype === 'image/jpg' ||
      file.mimetype === 'image/jpeg'
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
});

module.exports = {
    createUser,
    login,
    afterLogin,
    initUserInfo,
    updateUserBasicInfo,
    getUserAllInfo,
    uploadAvatar,
    upload,
    checkAdminPermission,
    getAllUsers,
    getAvatar,
    deleteUserById,
    updateUserById
};
